package ro.ubbcluj.cs.damate.plugin.utils;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class SavedDataUtils {

    @Autowired
    private DamateLogger log;

    @Value("${damate.plugin.dataDirectory}")
    private String pluginDataDirectory;

    public File getBaseDirectoryOfSavedData() {
        if (System.getProperty("user.home") != null) {
            File userHomeDir = new File(System.getProperty("user.home"));
            if (userHomeDir.exists() && userHomeDir.isDirectory() && userHomeDir.canWrite()) {
                return new File(userHomeDir.getAbsolutePath() + "/.damate/cache");
            }
        }
        return new File(pluginDataDirectory+"/cache");
    }

    public boolean hasAuthenticationToken() {
        return new File(getBaseDirectoryOfSavedData(), "token").exists();
    }

    public String getAuthenticationToken() {
        if (hasAuthenticationToken()) {
            try {
            	return FileUtils.readFileToString(new File(getBaseDirectoryOfSavedData(), "token"), "UTF-8");                
            } catch (IOException e) {
                log.error("Cannot load the saved token for the authentication. The login dialog will be displayed to validate the user.", e);
            }
        }
        return null;
    }

    public void setAuthenticationToken(String token) {
        try {
            if (!getBaseDirectoryOfSavedData().exists()) {
                getBaseDirectoryOfSavedData().mkdirs();
            }
            if (StringUtils.isNotEmpty(token)) {
                FileUtils.writeStringToFile(new File(getBaseDirectoryOfSavedData(), "token"), token, "UTF-8");
            }
        } catch (IOException e) {
            log.error("Cannot save the authentication token.", e);
        }
    }

    public void clearCache() {
        try {
            FileUtils.deleteDirectory(getBaseDirectoryOfSavedData());
        } catch (IOException e) {
            log.error("Cannot clean the cache directory.", e);
        }
    }
}
